<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/8
 * Time: 14:36
 */

namespace bgb\baidu;

use bgb\Http;

/**
 * 百度ai技术api接口类
 * Class Aip
 * @package bgb\baidu
 */
class AipOcr
{
    use Http;

    const ACCESS_TOKEN_KEY = 'BAIDU_AI_ACCESS_TOKEN';

    const OCR_IDCARD_URL = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard'; //身份证识别

    const OCR_BANKCARD_URL = 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard'; //银行卡识别

    protected static $instance;

    protected $appkey;
    protected $appsecret;
    protected $cacheKey;

    /**
     * 初始化方法
     * AipOcr constructor.
     * @param $appkey
     * @param $appsecret
     */
    public function __construct($appkey, $appsecret)
    {
        $this->appkey = $appkey;
        $this->appsecret = $appsecret;
        $this->cacheKey = 'appkey:' . $appkey . ':appsecret:' . $appsecret;
    }

    /**a
     * 获取对应 appid 以及 appsecret 单例
     * @param $appkey
     * @param $appsecret
     * @return $this
     */
    public static function getInstance($appkey, $appsecret)
    {
        $key = 'appkey:' . $appkey . ':appsecret:' . $appsecret;

        if (!isset(self::$instance[$key])) {
            self::$instance[$key] = new static($appkey, $appsecret);
        }

        return self::$instance[$key];

    }

    /**
     * 获取accesstoken 1个月过期 需要定时维护
     * @return mixed
     */
    public function getOrSetAccessToken()
    {
        $accessToken = cache($this->cacheKey);
        if (!$accessToken) {
            $accessTokenResult = $this->_getToken();

            if ($accessTokenResult['status'] == false) {
                return false;
            } else {
                $accessTokenInfo = $accessTokenResult['data'];
                cache($this->cacheKey, $accessTokenInfo['access_token'], $accessTokenInfo['expires_in']);
            }

        }

        return $accessToken;
    }

    /**
     * 获取token
     * @return array|mixed
     */
    private function _getToken()
    {
        $result = $this->postRequest('https://aip.baidubce.com/oauth/2.0/token', [
            'grant_type' => 'client_credentials',
            'client_id' => $this->appkey,
            'client_secret' => $this->appsecret
        ]);

        if (isset($result['error'])) {
            return ['status' => false, 'msg' => $result['error_description']];
        }

        return ['status' => true, 'data' => $result];
    }

    /**
     * 身份证识别 http://ai.baidu.com/docs#/OCR-API/top
     * @param $image string 身份证识别图片地址
     * @param string $idCardSide front：身份证含照片的一面；back：身份证带国徽的一面
     * @param bool $detectDirection 是否检测图像旋转角度
     * @param bool $detectRisk 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能
     * @return bool|mixed
     */
    public function idCard($image, $idCardSide = 'front', $detectDirection = false, $detectRisk = false)
    {
        $accessToken = $this->getOrSetAccessToken();

        if (!$accessToken) {
            return false;
        }

        $url = self::OCR_IDCARD_URL . '?access_token=' . $accessToken;

        $img = base64_encode(file_get_contents($image));

        return $this->postRequest($url, [
            'image' => $img,
            'detect_direction' => $detectDirection,
            'id_card_side' => $idCardSide,
            'detect_risk' => $detectRisk
        ]);

    }

    /**
     * 银行卡识别 http://ai.baidu.com/docs#/OCR-API/top
     * @param $image string 图像数据
     * @return bool|mixed
     */
    public function bankCard($image)
    {
        $accessToken = $this->getOrSetAccessToken();
        if (!$accessToken) {
            return false;
        }

        $url = self::OCR_BANKCARD_URL . '?access_token=' . $accessToken;

        return $this->postRequest($url, ['image' => base64_encode(file_get_contents($image))]);

    }

}